from flask import Flask, jsonify
from flask_cors import CORS
from pydantic import ValidationError

from web.device_controller import device_blueprint
from web.slave_controller import slave_blueprint

import argparse
import signal
import sys


def create_app():
    # 初始化Flask应用
    app = Flask(__name__, static_url_path="/")
    app.register_blueprint(device_blueprint)
    app.register_blueprint(slave_blueprint)
    # 开启跨域
    CORS(app, supports_credentials=True)
    return app


app = create_app()


# 全局错误处理器
@app.errorhandler(ValidationError)
def handle_validation_error(error: ValidationError):
    errors = []
    for err in error.errors():
        errors.append({
            "field": err["loc"][0],  # 错误字段
            "message": err["msg"],  # 错误描述
            "type": err["type"]  # 错误类型（如 "missing"）
        })
    return jsonify({"code": 422, "message": errors, "data": None}), 422


# argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('--port', type=int, default=8000, help='The port number.')
args = parser.parse_args()


# 通过信号来退出服务，否则会出现终端显示退出后，实际进程仍在运行
# 定义信号处理函数
def signal_handler(sig, frame):
    print("[python] [flask] Received signal to terminate the server:", sig)
    sys.exit(0)


# 注册信号处理函数
signal.signal(signal.SIGTERM, signal_handler)
signal.signal(signal.SIGINT, signal_handler)

if __name__ == "__main__":
    app.run(debug=False, host='0.0.0.0', port=args.port)
